
#include "../../../inc/Ui/GoogleBuzz/GoogleBuzzTokenForm.h"
#include "../../../inc/Ui/GoogleBuzz/GoogleBuzzMenuForm.h"

using namespace Osp::Base;
using namespace Osp::Ui;
using namespace Osp::Ui::Controls;


GoogleBuzzTokenForm::GoogleBuzzTokenForm(void)
{
	code = L"";
	clientID = L"306001726449-fc06vh80bfdq0ngehpbfi991p3b2f6t0.apps.googleusercontent.com";
	clientSecret = L"fCYq_66_lVZljsmdOdqgHiQC";
	redirectUri = L"urn:ietf:wg:oauth:2.0:oob";
	apiKey = L"AIzaSyDeX3wYvKbCQzJPIcrAF-Ytlj6dWeom5fA";
	pDownloadPopup = null;
}

GoogleBuzzTokenForm::~GoogleBuzzTokenForm(void)
{
}

bool
GoogleBuzzTokenForm::Initialize()
{
	Form::Construct(L"GoogleBuzzTokenForm");

	return true;
}

result
GoogleBuzzTokenForm::OnInitializing(void)
{
	result r = E_SUCCESS;

	// TODO: Add your initialization code here
	pWeb = static_cast<Web*>(GetControl(L"IDC_WEB"));
	if (pWeb != null){
		pWeb->SetLoadingListener(this);
	}

	this->SetSoftkeyActionId(SOFTKEY_1, ID_SOFTKEY_CANCEL);
	this->AddSoftkeyActionListener(SOFTKEY_1, *this);

	AppResource *pAppResource = Application::GetInstance()->GetAppResource();
	Bitmap *pBitmap1 = pAppResource->GetBitmapN("/blue/progressing00.png");
	Bitmap *pBitmap2 = pAppResource->GetBitmapN("/blue/progressing01.png");
	Bitmap *pBitmap3 = pAppResource->GetBitmapN("/blue/progressing02.png");
	Bitmap *pBitmap4 = pAppResource->GetBitmapN("/blue/progressing03.png");
	Bitmap *pBitmap5 = pAppResource->GetBitmapN("/blue/progressing04.png");
	Bitmap *pBitmap6 = pAppResource->GetBitmapN("/blue/progressing05.png");
	Bitmap *pBitmap7 = pAppResource->GetBitmapN("/blue/progressing06.png");
	Bitmap *pBitmap8 = pAppResource->GetBitmapN("/blue/progressing07.png");

	// Create AnimationFrames
	long duration = 500 / 8;
	AnimationFrame *pAniFrame1 = new AnimationFrame(*pBitmap1, duration);
	AnimationFrame *pAniFrame2 = new AnimationFrame(*pBitmap2, duration);
	AnimationFrame *pAniFrame3 = new AnimationFrame(*pBitmap3, duration);
	AnimationFrame *pAniFrame4 = new AnimationFrame(*pBitmap4, duration);
	AnimationFrame *pAniFrame5 = new AnimationFrame(*pBitmap5, duration);
	AnimationFrame *pAniFrame6 = new AnimationFrame(*pBitmap6, duration);
	AnimationFrame *pAniFrame7 = new AnimationFrame(*pBitmap7, duration);
	AnimationFrame *pAniFrame8 = new AnimationFrame(*pBitmap8, duration);

	animationFrameList.Construct();
	animationFrameList.Add(*pAniFrame1);
	animationFrameList.Add(*pAniFrame2);
	animationFrameList.Add(*pAniFrame3);
	animationFrameList.Add(*pAniFrame4);
	animationFrameList.Add(*pAniFrame5);
	animationFrameList.Add(*pAniFrame6);
	animationFrameList.Add(*pAniFrame7);
	animationFrameList.Add(*pAniFrame8);

	pAnimation = new Animation();
	pAnimation->Construct(Rectangle(130, 40, 120, 120), animationFrameList);
	pAnimation->SetRepeatCount(10000);
	pAnimation->AddAnimationEventListener(*this);

	return r;
}

void GoogleBuzzTokenForm::ShowPopup(){
	pDownloadPopup = new Popup();
	Dimension dim(300, 200);

	pDownloadPopup->Construct(false, dim);
	pDownloadPopup->AddControl(*pAnimation);
	//this->AddControl(*pDownloadPopup);
	pDownloadPopup->SetShowState(true);
	pDownloadPopup->Show();
	pAnimation->Play();
}

void GoogleBuzzTokenForm::GetTokent(){
	pWeb->LoadUrl(L"https://accounts.google.com/o/oauth2/auth?client_id=306001726449-fc06vh80bfdq0ngehpbfi991p3b2f6t0.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/buzz&response_type=code");
}

void GoogleBuzzTokenForm::OnActionPerformed(const Control &source, int actionId){
	FormManager *pFormManager = null;
	FormManager::GetInstance(pFormManager);

	Form *pForm = null;
	pFormManager->GetForm(GoogleBuzzMenuForm::GetFormId(), pForm);
	pForm->SendUserEvent(GoogleBuzzMenuForm::REQUEST_GET_TOKEN_CANCEL, null);

	pFormManager->SetCurrentForm(GoogleBuzzMenuForm::GetFormId());
}

void GoogleBuzzTokenForm::OnPageTitleReceived(const String &title){
	int index = 0;
	title.IndexOf("code", 0, index);
	if (index == -1){
		return;
	}

	title.SubString(index + 5, code);
	ShowPopup();
	String url = L"https://accounts.google.com/o/oauth2/token";

	String body = L"";
	body.Append(L"client_id="); body.Append(clientID);
	body.Append(L"&client_secret="); body.Append(clientSecret);
	body.Append(L"&code="); body.Append(code);
	body.Append(L"&redirect_uri="); body.Append(redirectUri);
	body.Append(L"&grant_type="); body.Append(L"authorization_code");

	ByteBuffer *pBody = null;
	pBody = Utility::StringUtil::StringToUtf8N(body);

	//HttpHeader *pHeader = new HttpHeader();
	HttpHeader *pHeader = new HttpHeader();

	pHeader->AddField(String(L"Content-Type"), String(L"application/x-www-form-urlencoded"));
	//pHeader->AddField();

	Download(url, pBody, pHeader, NET_HTTP_METHOD_POST);
}

void GoogleBuzzTokenForm::OnLoadingErrorOccurred (LoadingErrorType error, const Osp::Base::String &reason){

	String err = L"";
	Application *pApp = Application::GetInstance();
	pApp->GetAppResource()->GetString(L"IDS_GOOGLEBUZZGETTOKEN_LOADINDERROR", err);

	MessageBox message;
	message.Construct(String(L"Google buzz"), err, MSGBOX_STYLE_OK, 30000);
	int i;
	message.ShowAndWait(i);

	FormManager *pFormManager = null;
	FormManager::GetInstance(pFormManager);

	Form *pForm = null;
	pFormManager->GetForm(GoogleBuzzMenuForm::GetFormId(), pForm);
	pForm->SendUserEvent(GoogleBuzzMenuForm::REQUEST_GET_TOKEN_CANCEL, null);

	pFormManager->SetCurrentForm(GoogleBuzzMenuForm::GetFormId());
}

result
GoogleBuzzTokenForm::OnTerminating(void)
{
	result r = E_SUCCESS;

	// TODO: Add your termination code here
	animationFrameList.RemoveAll(true);
	if (pDownloadPopup != null){
		delete pDownloadPopup;
	}
	return r;
}

void GoogleBuzzTokenForm::Download(String url, ByteBuffer *pBody,
		HttpHeader *pHeader, NetHttpMethod method) {
	result r = E_SUCCESS;


	HttpSession *pSession = new HttpSession();
	r = pSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, null, url, null);

	if (IsFailed(r)) {
		AppLog("Googlebuzzform: That bai");
		return;
	}


	HttpTransaction *pTransaction = pSession->OpenTransactionN();
	if (pTransaction == null) {
		AppLog("Googlebuzzform: Can't open transaction");
		return;
	}

	pTransaction->AddHttpTransactionListener(*this);

	HttpRequest *pRequest = pTransaction->GetRequest();
	if (pRequest == null) {
		AppLog("Googlebuzzform: can't get request");
		return;
	}

	HttpHeader *pRequestHeader = pRequest->GetHeader();
	if (pHeader != null){
		IList *lstName = pHeader->GetFieldNamesN();
		int headerCount = lstName->GetCount();
		for (int i = 0; i < headerCount; i++){
			String *keyName = (String*)lstName->GetAt(i);
			IEnumerator *iEnum = pHeader->GetFieldValuesN(*keyName);
			iEnum->MoveNext();
			String *keyValue = (String*)iEnum->GetCurrent();
			pRequestHeader->AddField(*keyName, *keyValue);

		}
		delete lstName;
	}

	r = pRequest->SetUri(url);
	if (IsFailed(r)) {
		AppLog("Googlebuzzform: can't set url");
		return;
	}

	r = pRequest->SetMethod(method);
	if (IsFailed(r)) {
		AppLog("Googlebuzzform: can't set method");
		return;
	}

	if (pBody != null){
		int length = pBody->GetLimit() - 1;
		String lengthAsString = L"";
		lengthAsString.Append(length);
		pBody->SetPosition(0);
		pRequestHeader->AddField("Content-Length", lengthAsString);
		pTransaction->EnableTransactionReadyToWrite();
		pRequest->WriteBody(*pBody);
	}


	r = pTransaction->Submit();

	if (IsFailed(r)) {
		AppLog("Googlebuzzform: can't submit");

	}
//	delete pTransaction;
	if (pBody != null){
		delete pBody;
	}
	if (pHeader != null){
		delete pHeader;
	}
}

void GoogleBuzzTokenForm::ProcessGetToken(HttpSession &httpSession, HttpTransaction &httpTransaction){
	HttpResponse* pResponse = httpTransaction.GetResponse();

	NetHttpStatusCode statusCode = pResponse->GetStatusCode();

	ByteBuffer* pBody = pResponse->ReadBodyN();
	int limit = pBody->GetLimit();
	pBody->Flip(POSITION_TO_ZERO);
	pBody->SetLimit(limit);

	if (statusCode != NET_HTTP_STATUS_OK) {
		AppLog("Failed");
	}

	JsonReader reader;
	JsonObject object;

	reader.read(pBody, object);
	JsonString *jsonString = null;
	jsonString = (JsonString*)object.getValueN(L"access_token");
	this->accessToken = jsonString->getValue();
	delete jsonString;
	jsonString = (JsonString*)object.getValueN(L"refresh_token");
	this->refreshToken = jsonString->getValue();
	delete jsonString;
	AppLog("Xong rùi");

	//delete pEncoder;
	delete pBody;

	ArrayList *pListArg = new ArrayList();
	pListArg->Construct();
	pListArg->Add(*(new String(accessToken)));
	pListArg->Add(*(new String(refreshToken)));

	FormManager *pFormManager = null;
	FormManager::GetInstance(pFormManager);

	Form *pForm = null;
	pFormManager->GetForm(GoogleBuzzMenuForm::GetFormId(), pForm);
	pAnimation->Stop();

	pFormManager->SetCurrentForm(GoogleBuzzMenuForm::GetFormId());
	pForm->SendUserEvent(GoogleBuzzMenuForm::REQUEST_GET_TOKEN_OK, pListArg);
}

void GoogleBuzzTokenForm::OnTransactionReadyToRead(HttpSession &httpSession,
		HttpTransaction &httpTransaction, int availableBodyLen) {
	AppLog("Vao  on transaction ready to read");
	ProcessGetToken(httpSession, httpTransaction);
}
